ICollection
ICollection — Countable, Modifiable Collections
"Use ICollection
when you need Count without enumeration, and callers may Add/Remove items."
❌ Bad example:
public IEnumerable<Position> GetPositions()
{
return _positions.Where(p => p.IsOpen);
}
// Caller
public void ValidatePositions(IEnumerable<Position> positions)
{
int count = positions.Count(); // enumerates entire sequence
if (count > MaxPositions)
throw new InvalidOperationException("Too many positions");
}
Using .Count() on IEnumerable
✅ Good example:
public ICollection<Position> GetPositions()
{
return _positions.Where(p => p.IsOpen).ToList();
}
// Caller
public void ValidatePositions(ICollection<Position> positions)
{
if (positions.Count > MaxPositions) // O(1) property access
throw new InvalidOperationException("Too many positions");
}
👉 ICollection
🔥 When Add/Remove matters:
public interface IOrderQueue
{
ICollection<Order> PendingOrders { get; }
}
public class OrderProcessor
{
private readonly IOrderQueue _queue;
public void CancelOrder(int orderId)
{
var order = _queue.PendingOrders.FirstOrDefault(o => o.Id == orderId);
if (order != null)
_queue.PendingOrders.Remove(order); // mutation supported
}
}
👉 Callers can modify the collection via Add/Remove without exposing concrete type.
💡 In trading systems:
- Use ICollection
for position snapshots where count validation is critical. - Expose ICollection
when callers need to add/remove pending orders or alerts. - Prefer IEnumerable
if Count isn't needed—keeps API minimal.
---
Questions & Answers
Q: What's the difference between IEnumerable
A: ICollection
Q: Does ICollection
A: Not strictly, but most implementations (List
Q: Should I return ICollection
A: Only if callers legitimately need Count or Add/Remove. Otherwise, IEnumerable
Q: Can I expose ICollection
A: Use IReadOnlyCollection
Q: What's the risk of returning ICollection
A: Callers can mutate the collection, potentially breaking invariants. Return defensive copies or IReadOnlyCollection
Q: How does ICollection
A: Arrays implement ICollection
Q: When should I use HashSet
A: HashSet
Q: Can ICollection
A: No. Count property implies materialization. Returning ICollection
Q: How do I mock ICollection
A: Use List
Q: What's the performance of Contains() on ICollection
A: Depends on implementation. HashSet